package com.xmy.cultivate.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.entity.views.face.FaceGetScheduling;
import com.xmy.cultivate.exception.CommonException;
import com.xmy.cultivate.mapper.CourseMapper;
import com.xmy.cultivate.mapper.CourseSchedulingDetailMapper;
import com.xmy.cultivate.mapper.GradeMapper;
import com.xmy.cultivate.service.IFaceStudentService;
import com.xmy.cultivate.service.IQuarterService;
import com.xmy.cultivate.service.IStudentSignInService;
import com.xmy.cultivate.util.ResultCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class FaceStudentServiceImpl implements IFaceStudentService {


    @Autowired
    CourseSchedulingDetailMapper courseSchedulingDetailMapper;

    @Autowired
    IQuarterService iQuarterService;

    @Autowired
    IStudentSignInService iStudentSignInService;

    @Autowired
    GradeMapper gradeMapper;

    @Autowired
    CourseMapper courseMapper;

    /**
     * 获取今日上课信息
     * @param schoolId
     * @param studentId
     * @return
     */
    @Override
    public FaceGetScheduling getCourseSchedulingDetail(Long schoolId, Long studentId) {

        Quarter quarter = iQuarterService.getNowQuarter();
        if(quarter == null){
            throw new CommonException(ResultCode.quarterNo);
        }
        LocalDate nowDate = LocalDate.now();

        LocalDateTime nowDateTime = LocalDateTime.now().withNano(0);

        QueryWrapper<CourseSchedulingDetail> courseSchedulingDetailQueryWrapper = new QueryWrapper<>();
        courseSchedulingDetailQueryWrapper.eq("school_date",nowDate);
        courseSchedulingDetailQueryWrapper.eq("school_id",schoolId);
        courseSchedulingDetailQueryWrapper.inSql("grade_id","select grade_id from student_grade where status = 1 and reading_status=1 and year_part = "+quarter.getYearPart()+" and quarter_num="+quarter.getNum()+" and student_id = "+studentId+"");
        courseSchedulingDetailQueryWrapper.orderByAsc("start_date_time");

        List<CourseSchedulingDetail>  courseSchedulingDetailList = courseSchedulingDetailMapper.selectList(courseSchedulingDetailQueryWrapper);

        CourseSchedulingDetail courseSchedulingDetailInfo = null;
        FaceGetScheduling faceGetScheduling = new FaceGetScheduling();
        QueryWrapper<StudentSignIn> studentSignInQueryWrapper = null;

        Integer schedulingCount = courseSchedulingDetailList.size();
        //如果只是存在一条数据
        if(schedulingCount == 1){
            faceGetScheduling.setCourseType(1);//1精品课，2智能课
            for (CourseSchedulingDetail courseSchedulingDetail:courseSchedulingDetailList){
                courseSchedulingDetailInfo = courseSchedulingDetail;
                studentSignInQueryWrapper = new QueryWrapper<>();
                studentSignInQueryWrapper.eq("scheduling_detail_id",courseSchedulingDetail.getId());
                studentSignInQueryWrapper.eq("student_id",studentId);
                studentSignInQueryWrapper.last("limit 1");

                //打卡记录
                StudentSignIn studentSignIn = iStudentSignInService.getOne(studentSignInQueryWrapper);
                Duration duration = Duration.between(nowDateTime, courseSchedulingDetailInfo.getStartDateTime());
                long minutsStart = duration.toMinutes();//上课相差分钟
                Duration durationEnd = Duration.between(nowDateTime, courseSchedulingDetailInfo.getEndDateTime());
                long minutsEnd = durationEnd.toMinutes();//下课相差分钟


                //获取班级
                Grade grade = gradeMapper.selectById(courseSchedulingDetail.getGradeId());
                if(grade!=null){
                    faceGetScheduling.setGradeName(grade.getName());
                    Course course = courseMapper.selectById(grade.getCourseId());
                    if(course != null){
                        faceGetScheduling.setCourseName(course.getName());
                        faceGetScheduling.setSubjectsId(course.getSubjectsId());
                    }
                }

                if(studentSignIn == null){
                    //faceGetScheduling.setSchedulingDetailId(courseSchedulingDetail.getId());
                    //faceGetScheduling.setSubjectsId(courseSchedulingDetail.getSubjectsId());
                    if(minutsStart>60){
                        faceGetScheduling.setType(5);//还未到签到时间
                        faceGetScheduling.setStatus(1);
                    }else if(minutsStart<=60 && minutsEnd>10){
                        faceGetScheduling.setSchedulingDetailId(courseSchedulingDetail.getId());
                        faceGetScheduling.setSubjectsId(courseSchedulingDetail.getSubjectsId());
                        faceGetScheduling.setType(1);//签到
                        faceGetScheduling.setStatus(1);
                    }else if(minutsEnd >-60){
                        faceGetScheduling.setSchedulingDetailId(courseSchedulingDetail.getId());
                        faceGetScheduling.setSubjectsId(courseSchedulingDetail.getSubjectsId());
                        faceGetScheduling.setType(2);//签退
                        faceGetScheduling.setStatus(1);
                    }else{
                        faceGetScheduling.setType(7);//已超过签退时间
                        faceGetScheduling.setStatus(1);
                    }
                }else {
                    faceGetScheduling.setSignInId(studentSignIn.getId());
                    if(studentSignIn.getOutDateTime()==null){
                        Duration durationInDate = Duration.between(nowDateTime, studentSignIn.getInDateTime());
                        long minutsInDate = duration.toMinutes();
                        //是否离上课打卡后20分钟（20分钟后才能签退）
                        if(minutsEnd <10 && minutsEnd >-60){
                            //签退
                            faceGetScheduling.setSchedulingDetailId(courseSchedulingDetail.getId());
                            faceGetScheduling.setSubjectsId(courseSchedulingDetail.getSubjectsId());
                            faceGetScheduling.setType(2);//签退
                            faceGetScheduling.setStatus(1);
                        }else if(minutsEnd <20){
                            faceGetScheduling.setSchedulingDetailId(courseSchedulingDetail.getId());
                            faceGetScheduling.setSubjectsId(courseSchedulingDetail.getSubjectsId());
                            faceGetScheduling.setType(5);//还未到签退时间
                            faceGetScheduling.setStatus(1);
                        }else if(minutsInDate<10){
                            faceGetScheduling.setSchedulingDetailId(courseSchedulingDetail.getId());
                            faceGetScheduling.setSubjectsId(courseSchedulingDetail.getSubjectsId());
                            faceGetScheduling.setType(3);//已签到
                            faceGetScheduling.setStatus(1);
                        }
                    }else {
                        faceGetScheduling.setType(4);//已签退
                        faceGetScheduling.setStatus(1);
                        faceGetScheduling.setSchedulingDetailId(courseSchedulingDetail.getId());
                        faceGetScheduling.setSubjectsId(courseSchedulingDetail.getSubjectsId());
                    }
                }
                //System.out.println("minuts:"+minutsStart);
            }
        }
        else if(schedulingCount >1){
            faceGetScheduling.setCourseType(1);//1精品课，2智能课
            for (int i = 0; i < (schedulingCount-1); i++) {
                //判断是否已经有值
                if(faceGetScheduling.getSchedulingDetailId() == null){
                    CourseSchedulingDetail courseSchedulingDetail = courseSchedulingDetailList.get(i);
                    courseSchedulingDetailInfo = courseSchedulingDetail;

                    //下一条
                    Long minutsStartNext = null;
                    if(i<(schedulingCount-1)){
                        CourseSchedulingDetail nextCourseSchedulingDetail = courseSchedulingDetailList.get(i+1);
                        //距离下一节开始时间
                        Duration durationStartNext = Duration.between(nowDateTime, nextCourseSchedulingDetail.getStartDateTime());
                        minutsStartNext = durationStartNext.toMinutes();
                    }



                    //获取课程
                    Grade grade = gradeMapper.selectById(courseSchedulingDetail.getGradeId());
                    if(grade!=null){
                        faceGetScheduling.setGradeName(grade.getName());
                        Course course = courseMapper.selectById(grade.getCourseId());
                        if(course != null){
                            faceGetScheduling.setCourseName(course.getName());
                            faceGetScheduling.setSubjectsId(course.getSubjectsId());
                        }
                    }


                    Duration durationStart = Duration.between(nowDateTime, courseSchedulingDetailInfo.getStartDateTime());
                    long minutsStart = durationStart.toMinutes();
                    Duration durationEnd = Duration.between(nowDateTime, courseSchedulingDetailInfo.getEndDateTime());
                    long minutsEnd = durationEnd.toMinutes();

                    studentSignInQueryWrapper = new QueryWrapper<>();
                    studentSignInQueryWrapper.eq("scheduling_detail_id",courseSchedulingDetail.getId());
                    studentSignInQueryWrapper.eq("student_id",studentId);
                    studentSignInQueryWrapper.last("limit 1");
                    //打卡记录
                    StudentSignIn studentSignIn = iStudentSignInService.getOne(studentSignInQueryWrapper);

                    if(studentSignIn != null){
                        faceGetScheduling.setSignInId(studentSignIn.getId());

                        //已经打过签到与签退，跳过到下一条
                        if(studentSignIn.getOutDateTime()!=null){
                            if(minutsEnd<0 && minutsStartNext !=null && minutsStartNext<30){
                                //如果下一节课在30分钟内，就跳到下一节课，否则结束循环
                                continue;
                            }else {
                                faceGetScheduling.setSchedulingDetailId(courseSchedulingDetail.getId());
                                faceGetScheduling.setSubjectsId(courseSchedulingDetail.getSubjectsId());
                                faceGetScheduling.setType(4);//已签退
                                faceGetScheduling.setStatus(1);
                                break;
                            }
                        }
                        //在下课10分钟前
                        if(minutsStart>0 && minutsEnd>=10){
                            //已经签到过，直接结束
                            faceGetScheduling.setSchedulingDetailId(courseSchedulingDetail.getId());
                            faceGetScheduling.setSubjectsId(courseSchedulingDetail.getSubjectsId());
                            faceGetScheduling.setType(4);//不要重复签到或签退
                            faceGetScheduling.setStatus(1);
                            break;
                        }else if(minutsStart<0 && minutsEnd<10 && minutsEnd> -60 && studentSignIn.getOutDateTime()==null){
                            //在上课后，下课前10分钟后
                            //在下课后，一个小时内
                            faceGetScheduling.setSchedulingDetailId(courseSchedulingDetail.getId());
                            faceGetScheduling.setSubjectsId(courseSchedulingDetail.getSubjectsId());
                            faceGetScheduling.setType(2);//签退
                            faceGetScheduling.setStatus(1);
                            break;
                        }
                    }else {
                        //在上课前60分钟内
                        if(minutsStart>0 && minutsStart<60){
                            faceGetScheduling.setSchedulingDetailId(courseSchedulingDetail.getId());
                            faceGetScheduling.setSubjectsId(courseSchedulingDetail.getSubjectsId());
                            faceGetScheduling.setType(1);//签到
                            faceGetScheduling.setStatus(1);
                            break;
                        }else if(minutsStart<0 && minutsEnd>=10){
                            //在上课后，下课前10分钟
                            faceGetScheduling.setSchedulingDetailId(courseSchedulingDetail.getId());
                            faceGetScheduling.setSubjectsId(courseSchedulingDetail.getSubjectsId());
                            faceGetScheduling.setType(1);//签到
                            faceGetScheduling.setStatus(1);
                            break;
                        }else if(minutsEnd<10 && minutsEnd> -60){
                            //在下课后，一个小时内
                            faceGetScheduling.setSchedulingDetailId(courseSchedulingDetail.getId());
                            faceGetScheduling.setSubjectsId(courseSchedulingDetail.getSubjectsId());
                            faceGetScheduling.setType(2);//签退
                            faceGetScheduling.setStatus(1);
                            break;
                        }
                    }
                }
            }
        }
        else{
            /*
            //智能课,不需要排课
            faceGetScheduling.setCourseType(2);//1精品课，2智能课
            studentSignInQueryWrapper = new QueryWrapper<>();
            studentSignInQueryWrapper.eq("scheduling_detail_id",0L);
            studentSignInQueryWrapper.eq("add_date",nowDate);
            studentSignInQueryWrapper.last("limit 1");

            faceGetScheduling.setGradeName("智能课");
            faceGetScheduling.setCourseName("智能课");
            //打卡记录
            StudentSignIn studentSignIn = iStudentSignInService.getOne(studentSignInQueryWrapper);
            if(studentSignIn == null){
                faceGetScheduling.setSchedulingDetailId(0L);
                faceGetScheduling.setType(1);//签到
                faceGetScheduling.setStatus(1);
            }else {

                Duration durationStart = Duration.between(nowDateTime, studentSignIn.getInDateTime());
                Long minutsStart = durationStart.toMinutes();

                if(studentSignIn.getInDateTime()!=null && studentSignIn.getOutDateTime() == null){
                    //离签到30分钟以上
                    if(minutsStart>30){
                        faceGetScheduling.setSchedulingDetailId(0L);
                        faceGetScheduling.setType(2);//签退
                        faceGetScheduling.setStatus(1);
                    }else {
                        faceGetScheduling.setSchedulingDetailId(0L);
                        faceGetScheduling.setType(4);//不要重复
                        faceGetScheduling.setStatus(1);
                    }
                }else if(studentSignIn.getInDateTime()==null && studentSignIn.getOutDateTime() != null){
                    faceGetScheduling.setSchedulingDetailId(0L);
                    faceGetScheduling.setType(4);//不要重复
                    faceGetScheduling.setStatus(1);
                }
            }*/
        }

        return faceGetScheduling;
    }
}
